import axios from 'axios';

const BASE_URL = ''; // 方便mock拦截，使用相对路径

export const instance = axios.create({
  baseURL: BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
  withCredentials: true,
  timeout: 10000,
});

instance.interceptors.request.use(
  (config) => {
    // 添加认证 token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    // 调试信息
    console.log('请求配置:', {
      url: config.url,
      method: config.method,
      params: config.params,
      data: config.data
    });
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  (response) => {
    // 调试响应数据
    console.log('响应数据:', response.data);
    return response;
  },
  (error) => {
    console.error('请求错误:', error);
    return Promise.reject(error);
  }
);

/**
 * 通用请求方法
 * @param {string} url 请求地址
 * @param {object} options axios 配置项
 * @returns {Promise<any>}
 */
export async function request(url, options = {}) {
  const paramRegex = /:([a-zA-Z0-9_]+)/g;
  let finalUrl = url;
  if (options.params) {
    finalUrl = url.replace(paramRegex, (_, key) => {
      // 如果参数存在则替换，否则保留原样
      return options.params[key] !== undefined ? encodeURIComponent(options.params[key]) : `:${key}`;
    });
  }
  console.log('Request URL:', finalUrl);
  console.log('Request Options:', options);

  try {
    const response = await instance.request({
      url: finalUrl,
      ...options,
    });
    
    // 确保返回数据是正确的
    console.log('Response Data Type:', typeof response.data);
    console.log('Response Data:', response.data);
    
    return response.data;
  } catch (error) {
    // 统一错误处理
    console.error('Request Error:', error);
    if (error.response) {
      throw { status: error.response.status, ...error.response.data };
    }
    throw error;
  }
}

// 常用方法封装
export const get = (url, options) =>
  request(url, { ...options, method: 'GET' });

export const post = (url, data, options) =>
  request(url, { ...options, method: 'POST', data });

export const put = (url, data, options) =>
  request(url, { ...options, method: 'PUT', data });

export const del = (url, options) =>
  request(url, { ...options, method: 'DELETE' });

